#/usr/bin/python
#coding:utf-8

import web
from url import urls
import sqlite3
import sys, os

path = os.path.dirname(os.path.realpath(__file__))  
sys.path.append(path) 
print path

render = web.template.render('templates', base = 'layout')
app = web.application(urls, globals(), autoreload=True)

#连接数据库
conn = sqlite3.connect('movie.db',check_same_thread=False)
cur = conn.cursor()

class list: #index
    def GET(self):
        p = page()
        return p.GET(1)
       

class test:
    def GET(self):
        return render.test()

class layout:
    def GET(self):
        return render.layout()

#电影简介
class detail:
    def GET(self,movieid):
        sql = 'select id, mname, mdate, detail2 from movie where id = %s' %movieid
        cur.execute(sql)
        res = cur.fetchone()
        
        return render.detail(res)

#电影列表
class page:
    def GET(self,page):
        perpage = 10
        cur.execute('select count(*) from movie')
        total = int(cur.fetchone()[0])
        if total % perpage == 0:
            
            pages = total / perpage
        else:
            pages = total / perpage + 1
        offnum = (int(page)-1) * perpage
        sql = 'select id, mname, mdate, detail1 from movie order by id limit %s Offset %s' %(perpage, offnum)
        cur.execute(sql)
        res = cur.fetchall()
        return render.list(res, page, pages)

class search:
    def GET(self):
        user_data = web.input(s="no data", p = "1")
        mname = user_data['s']
        page = user_data['p']
        #return mname + page 
        #return data['s'] + data['p']
        if mname == "":
           return web.seeother('/')
        else:
            perpage = 10

            cur.execute('select id, mname, mdate, detail1 from movie where mname like ? order by id', ['%' + mname + '%'])
            res = cur.fetchall()
            total = len(res)
            
            if total == 0:
                return web.seeother('/')
            else:
                if total % perpage == 0:
                    pages = total / perpage
                else:
                    pages = total / perpage + 1
            offnum = (int(page)-1) * perpage
            cur.execute('select id, mname, mdate, detail1 from movie where mname like ? order by id limit ? Offset ?', [('%' + mname + '%'), perpage, offnum])
            res = cur.fetchall()
                    
            return render.search(res, page, pages,mname)


if __name__ == '__main__':
    app.run()

